package com.cxb.carrecorder;

import java.io.File;
import java.util.List;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Environment;
import android.view.Window;

public class MainActivity extends Activity {
	private String szPath = null;// LOGÎÄ¼þ±£´æÂ·¾¶
	MyReceiver receiver;
	public static final String ACTION_FINISH_SELF = "android.intent.action.ACTION_FINISH_SELF";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		getWindow().requestFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.main_activity);

		if (CarRecorderDebug.DEBUG)
			szPath = Environment.getExternalStorageDirectory() + "/log.txt";
		CarRecorderDebug.printf("MainActivity.onCreate", szPath);
 
		receiver = new MyReceiver();

		/**
		 * ��ʹ���Զ��رգ����ù㲥���չر�
		 */
		IntentFilter filter = new IntentFilter();
		filter.addAction(ACTION_FINISH_SELF);
		registerReceiver(receiver, filter);

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub

		Intent intent = new Intent(MainActivity.this,
				PreviewService.class);
		intent.putExtra("setup_ui", true);
		startService(intent);
		super.onResume();
	}

	public static boolean isServiceRunning(Context mContext, String className) {
		boolean isRunning = false;
		ActivityManager activityManager = (ActivityManager) mContext
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningServiceInfo> serviceList = activityManager
				.getRunningServices(30);
		if (!(serviceList.size() > 0)) {
			return false;
		}
		for (int i = 0; i < serviceList.size(); i++) {
			if (serviceList.get(i).service.getClassName().equals(className) == true) {
				isRunning = true;
				break;
			}
		}
		return isRunning;
	}

	@Override
	protected void onDestroy() {
		CarRecorderDebug.printf("MainActivity.onDestroy", szPath);
		if (receiver != null)
			unregisterReceiver(receiver);
		super.onDestroy();
	}

	class MyReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			String msg = intent.getAction();
			if (msg.equals(ACTION_FINISH_SELF)) {
				if (context instanceof Activity) {
					((Activity) context).finish();
				}
			}
		}

	}

}
